package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.socket.WebSocketServer;
import com.sky.vo.OrderReportVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.TurnoverReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO 用户下单数据传输对象
     */
    @Override
    public OrderSubmitVO addOrder(OrdersSubmitDTO ordersSubmitDTO) {
        log.info("用户下单：{}", ordersSubmitDTO);
        // 1.数据校验（地址不为空，购物车不为空）
        Long userId = BaseContext.getCurrentId();
        // 地址不为空
        AddressBook addressBook = new AddressBook();
        addressBook.setId(ordersSubmitDTO.getAddressBookId());
        addressBook.setUserId(userId);
        addressBook = addressBookMapper.selectById(addressBook);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 购物车不为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2.新增订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.insert(orders);

        // 3.新增订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(sc -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(sc, orderDetail);
            // 设置订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.insertBatch(orderDetailList);

        // 4.清空购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        // 5.封装VO返回结果
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 客户催单
     *
     * @param id 订单id
     */
    @Override
    public void reminderOrder(Long id) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 通过 websocket 向客户端浏览器发送消息
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2); // 1表示来单提醒 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 营业额统计
     *
     * @param begin 开始日期
     * @param end   结束日期
     * @return 营业额统计数据
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 构建日期范围列表
        List<LocalDate> dateList = this.getDateList(begin, end);
        // 构建营业额列表
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            // 日期格式转换为日期时间格式，并设置为当天最小/最大时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED); // 设置订单状态为已完成
            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null) {
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }
        // 封装返回数据
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin 开始日期
     * @param end   结束日期
     * @return 订单统计数据
     */
    @Override
    public OrderReportVO getOrdersReport(LocalDate begin, LocalDate end) {
        // 构建日期范围列表
        List<LocalDate> dateList = this.getDateList(begin, end);

        // 构建每日订单数/每日有效订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 根据日期转换每日日期时间范围
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 根据条件查询订单总数
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
            // 根据条件查询有效订单
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }

        // 构建订单总数/有效订单数/订单完成率
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = totalOrderCount != 0 ? (double) validOrderCount / totalOrderCount : 0.0;

        // 封装返回数据
        return OrderReportVO.builder()
                .dateList(this.joinList(dateList))
                .orderCountList(this.joinList(orderCountList))
                .validOrderCountList(this.joinList(validOrderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 订单分页查询
     *
     * @param ordersPageQueryDTO 分页查询参数
     * @return 分页查询结果
     */
    @Override
    public PageResult getOrderPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开始分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 根据条件分页查询操作
        Page<Orders> page = orderMapper.selectPage(ordersPageQueryDTO);
        // 封装分页结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id获取订单详情
     *
     * @param id 订单id
     * @return 订单详情
     */
    @Override
    public Orders getOrderById(Long id) {
        return orderMapper.selectById(id);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO 取消订单参数
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        // 设置取消订单相关字段
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        // 更新操作
        orderMapper.update(orders);
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO 接单参数
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(ordersConfirmDTO.getId());
        // 设置接单相关字段
        orders.setStatus(Orders.CONFIRMED);
        // 更新操作
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO 拒单参数
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        // 设置拒单相关字段
        orders.setStatus(Orders.REJECTION);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        // TODO: 退款操作
        orders.setPayStatus(Orders.REFUND);
        // 更新操作
        orderMapper.update(orders);
    }

    /**
     * 派单
     *
     * @param id 订单id
     */
    @Override
    public void deliveryOrder(Long id) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(id);
        // 设置派单相关字段
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        // 更新操作
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id 订单id
     */
    @Override
    public void completeOrder(Long id) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectById(id);
        // 设置完成订单相关字段
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        // 更新操作
        orderMapper.update(orders);
    }

    /**
     * 查询订单状态数量统计
     *
     * @return 订单状态数量
     */
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        Map<String, Object> map = new HashMap<>();
        // 根据订单状态查询数量
        map.put("status", Orders.TO_BE_CONFIRMED);
        Integer toBeConfirmed = orderMapper.countByMap(map);
        map.put("status", Orders.CONFIRMED);
        Integer confirmed = orderMapper.countByMap(map);
        map.put("status", Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = orderMapper.countByMap(map);

        // 封装返回结果数据
        return OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
    }

    /**
     * 构建日期范围列表
     *
     * @param begin 开始日期
     * @param end   结束日期
     * @return 日期范围列表
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 将列表转换为,分隔字符串
     *
     * @param list 列表
     * @return 字符串
     */
    private String joinList(List<?> list) {
        return StringUtils.join(list, ",");
    }
}
